import Vue from "vue";
import getUserTempId from "@/utils/userTempId";
import {reqLogin, reqLogout, reqUserInfo} from "@/apis";

const state = {
    userTempId: getUserTempId(),
    token: localStorage.getItem('token') || '',
    userInfo: {},
    vueElementLoading: false
}
const mutations = {
    UPDATE_LOADING(state, {bol}) {
        state.vueElementLoading = bol
    },
    //设置token
    SET_TOKEN_STATE(state, payload) {
        state.token = payload.token
    },
    //设置用户信息
    SET_USERINFO_STATE(state, payload) {
        state.userInfo = payload.userInfo
    },
//    重置用户信息
    RESET_USERINFO_STATE(state) {
        state.token = ''
        state.userInfo = {}
        localStorage.removeItem('token')
    }
}
const actions = {
    //获取token
    async getToken({commit}, userInfo) {
        const [err, res] = await Vue.prototype.$to(reqLogin(userInfo))
        if (err) return Promise.reject(err)
        localStorage.setItem('token', res.token)
        commit('SET_TOKEN_STATE', {token: res.token})
    },//15136673116
    //获取用户信息
    async getUserInfo({commit}) {
        try {
            const userInfo = await reqUserInfo()
            commit('SET_USERINFO_STATE', {userInfo})
        } catch (e) {
            return Promise.reject(e.message)
        }
    },
    //退出登录
    async logOutUser({commit}) {
        const [err] = await Vue.prototype.$to(reqLogout())
        if (err) return alert(err.message)
        commit('RESET_USERINFO_STATE')
    },
    // 重置
    resetUser({commit}) {
        commit('RESET_USERINFO_STATE')
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}